package com.github.tonydeng.fmj.utils;/**
 * Created by xiemw on 2019/3/1.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    private static Logger logger = LoggerFactory.getLogger(Md5Util.class);

    public static String md5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes(StandardCharsets.UTF_8));
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer(200);
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset] & 0xff;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.error("Md5加密异常", e);
            return null;
        }
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");

            md.update(origin.getBytes(StandardCharsets.UTF_8));
            BigInteger hash = new BigInteger(1, md.digest());
            resultString = hash.toString(16);
            if ((resultString.length() % 2) != 0) {
                resultString = "0" + resultString;
            }
        } catch (Exception exception) {
        }
        return resultString;
    }
}
